package com.fivium.bpd.editor;

import com.fivium.bpd.component.AbstractStage;
import com.fivium.bpd.component.BusinessProcessDefinition;
import com.fivium.bpd.component.EntryStage;
import com.fivium.bpd.component.ExitStage;
import com.fivium.bpd.component.StandardStage;
import com.mxgraph.model.mxCell;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;

public class GraphComponent extends mxGraphComponent
{
  double y = 0;
  
  public GraphComponent(mxGraph graph, BusinessProcessDefinition bpd)
  {
    super(graph);
    
    //setPageVisible(true);
    setGridVisible(true);
    setToolTips(true);
    getConnectionHandler().setCreateTarget(true);

    StyleManager.initialize(graph.getStylesheet());
    
    loadBPDShapes(bpd);
    
  }
  
  private void loadBPDShapes(BusinessProcessDefinition bpd)
  {
    graph.getModel().beginUpdate();
    
    for (EntryStage e : bpd.getEntryStageList()) {
      createStageVertex(e, StyleManager.BPD_ENTRY_STAGE);
    }
    
    for (StandardStage s : bpd.getStandardStageList()) {
      createStageVertex(s, StyleManager.BPD_STANDARD_STAGE);
    }
    
    for (ExitStage e : bpd.getExitStageList()) {
      createStageVertex(e, StyleManager.BPD_EXIT_STAGE);
    }
    
    graph.getModel().endUpdate();
  }
  
  private void createStageVertex(AbstractStage stage, String style)
  {
    Object parent = graph.getDefaultParent();
    
    stage.setY(stage.getY() + y);
    
    mxCell vertex = new mxCell(stage.getLabel() + "\n" + stage.getTitle(), stage, style);
    
    vertex.setVertex(true);
    vertex.setConnectable(true);
    
    graph.addCell(vertex, parent);
    
    y += stage.getHeight() + 10;
  }
}
